﻿using HDSmartCommunity.Device;
using IntelligentDataCollection.BUS;
using IntelligentDataCollection.Models;
using IntelligentDataCollection.Tool;
using System.Xml;

namespace IntelligentDataCollection.Device
{
    public class DeviceSerialData
    {
        public static List<DeviceInfo> device_list = new List<DeviceInfo>();
        public int StorageStart = 0;
        public int StorageCount = 0;
        public int Interval = 0;

        public void InitConfig()
        {
            StorageStart = Convert.ToInt32(AppSettingsHelper.Configuration["StorageStart"]);
            StorageCount = Convert.ToInt32(AppSettingsHelper.Configuration["StorageCount"]);
            Interval = Convert.ToInt32(AppSettingsHelper.Configuration["Interval"]);
        }

        public void NetWorkConnect()
        {
            Task t = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        if (device_list.Count > 0)
                        {
                            foreach (var item in device_list)
                            {
                                if (item.ConnectFlag == false)
                                {
                                    NetDevice koneDevice = new NetDevice();
                                    koneDevice.ConnectServer(item.DeviceIP, item.DevicePort);
                                }
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Log("连接服务端异常" + ex.ToString());
                    }

                    Task.Delay(10000).Wait();
                }
            });
        }

        public void CmdSend()
        {
            Task t = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        foreach (var item in device_list)
                        {
                            if (item.ConnectFlag == true && item.socket != null)
                            {
                                if (item.socket.Connected)
                                {
                                    item.socket.Send(item.cmd);
                                }
                                else
                                {
                                    item.ConnectFlag = false;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Log("发送命令异常" + ex.ToString());
                    }

                    Task.Delay(Interval).Wait();
                }
            });
        }

        public void GetAllDevice()
        {
            //创建xml文档
            XmlDocument xmldoc = new XmlDocument();

            //导入指定xml文件
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略文档里面的注释，注释也是节点，但是无法转换成XmlElement，所以这里不忽略，下面转换就报错
                                           //XmlReader是用liu需要using包起来，读完释放资源，防止占用
            using (XmlReader reader = XmlReader.Create("DeviceInfo.xml", settings))
            {
                xmldoc.Load(reader);
            }

            //获取根节点
            XmlElement areaxml = xmldoc.DocumentElement;

            //遍历根节点的子节点
            foreach (XmlElement area in areaxml.ChildNodes)
            {
                DeviceInfo Device = new DeviceInfo();
                Device.ConnectFlag = false;

                foreach (XmlElement child in area.ChildNodes)
                {
                    if (child.Name == "DeviceName")
                    {
                        Device.DeviceName = child.InnerText;
                    }
                    else if (child.Name == "DeviceIP")
                    {
                        Device.DeviceIP = child.InnerText;
                    }
                    else if (child.Name == "DevicePort")
                    {
                        Device.DevicePort = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "DeviceId")
                    {
                        Device.DeviceId = Convert.ToInt32(child.InnerText);
                    }
                }
                Device.cmd = GetQueryCmd(Device.DeviceId);
                device_list.Add(Device);
            }
        }

        public byte[] GetQueryCmd(int deviceid)
        {
            byte[] bytes = new byte[8];
            byte[] crc_data = new byte[6];
            crc_data[0] = (byte)deviceid;
            crc_data[1] = 0x03;
            byte[] add_start = Untils.toBytes(StorageStart - 1);
            crc_data[2] = add_start[1];
            crc_data[3] = add_start[0];
            byte[] add_count = Untils.toBytes(StorageCount);
            crc_data[4] = add_count[1];
            crc_data[5] = add_count[0];
            byte[] crc = Untils.Crc18(crc_data);
            Array.Copy(crc_data, 0, bytes, 0, crc_data.Length);
            bytes[6] = crc[1];
            bytes[7] = crc[0];
            return bytes;
        }
    }
}
